package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.adjust;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanAdjustDetailRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAdjustDetailSubTotalRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.response.SalesPlanSubTotalResponse;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAdjustDetailRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAdjustDetailSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.adjust.SalesPlanAdjustDetailQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.PageQuerySalesPlanAdjustDetailRequest;
import com.epoch.app.bcorder.model.dto.PageQuerySalesPlanAdjustDetailResponse;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.contract.dto.SubTotalCompanyCrmContractCountRequest;
import com.epoch.app.bcorder.sales_plan.contract.model.Contract;
import com.epoch.app.bcorder.sales_plan.contract.service.ContractService;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountRequest;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountResponse;
import com.epoch.app.bcorder.sales_plan.planscitemextend.service.PlanScItemExtendService;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.SubTotalSalesPlanLineRequest;
import com.epoch.app.bcorder.service.SalesPlanService;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.crunifiedinventory.model.dto.GetStoreInventoryAggreRequest;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-10-25 16:17
 */
@Service
public class SalesPlanAdjustDetailQueryServiceImpl implements SalesPlanAdjustDetailQueryService {
    Log log = Log.getLogger(SalesPlanAdjustDetailQueryServiceImpl.class);

    @Resource
    private SalesPlanAdjustDetailRepository salesPlanAdjustDetailRepository;

    @Autowired(required = false)
    private CrUnifiedInventoryService crUnifiedInventoryService;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private SalesPlanService salesPlanService;

    @Resource
    private SalesPlanQueryService salesPlanQueryService;

    @Resource
    private PlanScItemExtendService planScItemExtendService;

    @Resource
    private ContractService contractService;

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanAdjustDetailSDO>>> pageQuerySalesPlanAdjustDetailList(PageQueryPlanAdjustDetailRequest pageQueryPlanAdjustDetailRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(pageQueryPlanAdjustDetailRequest.getPlanId());
        enichQueryPlanAdjustDetailRequest(pageQueryPlanAdjustDetailRequest,salesPlan);
        PageResult<List<SalesPlanAdjustDetailSDO>> salesPlanAdjustDetailList = salesPlanAdjustDetailRepository.pageQuerySalesPlanAdjustDetailList(pageQueryPlanAdjustDetailRequest);
        if (null != salesPlanAdjustDetailList && null != salesPlanAdjustDetailList.getContent() && salesPlanAdjustDetailList.getContent().size() > 0) {
            pageResultConverter(salesPlanAdjustDetailList);
        }
        return Result.success(salesPlanAdjustDetailList);
    }

    private void enichQueryPlanAdjustDetailRequest(PageQueryPlanAdjustDetailRequest pageQueryPlanAdjustDetailRequest,SalesPlanSDO salesPlan){
        if (pageQueryPlanAdjustDetailRequest.getBizType() == null && StringUtil.isBlank(pageQueryPlanAdjustDetailRequest.getBizId())) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        SalesStatBizTypeEnum statBizType = SalesStatBizTypeEnum.getByOrganizationType(pageQueryPlanAdjustDetailRequest.getBizType());
        if (statBizType == null) {
            //查询月度计划，获取业务单元id
            String orgBusinessUnitCode = salesPlan.getOrgBusinessUnitCode();
            if (StringUtil.isBlank(orgBusinessUnitCode)) {
                log.info("subTotalSalesPlanAdjustDetail月度计划{}缺少业务单位编码", pageQueryPlanAdjustDetailRequest.getPlanId());
                throw new FacadeException("OTS-02-002-00-16-002");
            }
            statBizType = SalesStatBizTypeEnum.BUSINESS_UNIT;
            pageQueryPlanAdjustDetailRequest.setBizId(orgBusinessUnitCode);
            pageQueryPlanAdjustDetailRequest.setBizType(103);
        }

        switch (statBizType) {
            case SALESMAN:
                pageQueryPlanAdjustDetailRequest.setManageEmployeeId(pageQueryPlanAdjustDetailRequest.getBizId());
                break;
            case SALES_DEPARTMENT:
                pageQueryPlanAdjustDetailRequest.setOrgSalesDepartmentCode(pageQueryPlanAdjustDetailRequest.getBizId());
                break;
            case SALES_CHANNEL:
                pageQueryPlanAdjustDetailRequest.setOrgSalesChannelCode(pageQueryPlanAdjustDetailRequest.getBizId());
                break;
            case SALES_ORGANIZATION:
                pageQueryPlanAdjustDetailRequest.setOrgSalesOrganizationCode(pageQueryPlanAdjustDetailRequest.getBizId());
                break;
            case BUSINESS_UNIT:
                pageQueryPlanAdjustDetailRequest.setOrgBusinessUnitCode(pageQueryPlanAdjustDetailRequest.getBizId());
                break;
            default:
        }

        //计划调整详情页明细列表调整值是根据计划status来区分取值的 前端做不到将status传给后端 后端自己处理
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(pageQueryPlanAdjustDetailRequest.getAdjustId());
        Result<SalesPlanSDO> result = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        if (result.isSuccess() && null != result.getResult()) {
            if (result.getResult().getStatus() != null && result.getResult().getStatus().intValue() == 4) {
                pageQueryPlanAdjustDetailRequest.setStatus(4);
            }
        }else{
            throw new FacadeException(ErrorMessage.code("OTS-02-002-00-16-001"));
        }
    }

    private void pageResultConverter(PageResult<List<SalesPlanAdjustDetailSDO>> salesPlanAdjustDetailList) {
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        salesPlanAdjustDetailList.getContent().forEach(salesPlanLineSDO -> {
            scItemSet.add(salesPlanLineSDO.getScItemId());
            if (StringUtils.isNotBlank(salesPlanLineSDO.getCustomerAddress())) {
                customerAddressSet.add(salesPlanLineSDO.getCustomerAddress());
            }
            customerSet.add(salesPlanLineSDO.getCustomerCode());
            orgSalesOrganizationCodeSet.add(salesPlanLineSDO.getOrgSalesOrganizationCode());
            channelCodeSet.add(salesPlanLineSDO.getChannelCode());
        });
        //获取货品外部编码
        Map<String, ScItemSDO> scItemMapByOutMap = salesPlanOutCommonService.getScItemMapByIds(scItemSet, false);
        if (null == scItemMapByOutMap){
            log.error("SalesPlanAdjustDetailQueryServiceImpl.pageResultConverter scItemMapByOutMap is null, scItemSet=" + scItemSet);
            return;
        }
        //获取客户地址
        Map<String, CustomerAddressIndex> customerAddressByFive = salesPlanOutCommonService.getCustomerAddressByFive(customerAddressSet, customerSet, orgSalesOrganizationCodeSet, channelCodeSet, null);
        if (null == customerAddressByFive){
            log.error("SalesPlanAdjustDetailQueryServiceImpl.pageResultConverter customerAddressByFive is null, customerAddress=" + customerAddressSet + ", customerSet=" + customerSet + ", orgSet=" + orgSalesOrganizationCodeSet);
            return;
        }
        List<String> addressIdCollect = customerAddressByFive.values().stream().map(index -> {
            return Objects.toString(index.getId());
        }).collect(Collectors.toList());

        //取门店库存
        Map<String, WarehouseInventory> businessInventoryMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(addressIdCollect)) {
            GetStoreInventoryAggreRequest getStoreInventoryAggreRequest = new GetStoreInventoryAggreRequest();
            getStoreInventoryAggreRequest.setAddressCodeList(addressIdCollect);
            getStoreInventoryAggreRequest.setGoodsIds(Lists.newArrayList(scItemSet));
            try {
                Result<List<WarehouseInventory>> listResult = crUnifiedInventoryService.getStoreInventoryAggre(getStoreInventoryAggreRequest);
                if (listResult != null && listResult.isSuccess() && CollectionUtils.isNotEmpty(listResult.getResult())){
                    businessInventoryMap = listResult.getResult().stream().collect(Collectors.toMap(x -> x.getGoodsId() + x.getAddressCode(), a -> a, (a, b) -> a));
                }
            }catch (Exception e){
                log.error("SalesPlanAdjustDetailQueryServiceImpl.searchBusinessInventoryByPage.exception:{}",e);
            }
        }

        for (SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO : salesPlanAdjustDetailList.getContent()) {
            salesPlanAdjustDetailSDO.setInventory(0);
            if (!Objects.isNull(scItemMapByOutMap) && !scItemMapByOutMap.isEmpty()) {
                ScItemSDO scItemSDO = scItemMapByOutMap.get(salesPlanAdjustDetailSDO.getScItemId());
                if (Objects.nonNull(scItemSDO)) {
                    //外部编码
                    salesPlanAdjustDetailSDO.setOuterId(scItemSDO.getOuterId());
                }
            }
            CustomerAddressIndex customerAddressIndex = customerAddressByFive.get(salesPlanAdjustDetailSDO.getCustomerCode() + salesPlanAdjustDetailSDO.getCustomerAddress() + salesPlanAdjustDetailSDO.getOrgSalesOrganizationCode() + salesPlanAdjustDetailSDO.getChannelCode());
            if (customerAddressIndex == null) {
                salesPlanAdjustDetailSDO.setInventoryStr("0");
                continue;
            }
            WarehouseInventory warehouseInventory = businessInventoryMap.get(salesPlanAdjustDetailSDO.getScItemId() + customerAddressIndex.getId());
            if (Objects.nonNull(warehouseInventory)) {
                salesPlanAdjustDetailSDO.setInventoryStr(warehouseInventory.getAvailableQuantityFormat());
            } else {
                salesPlanAdjustDetailSDO.setInventoryStr("0");
            }
        }
    }

    @Override
    @FacadeInvoker
    public Result<SalesPlanSubTotalResponse> subTotalSalesPlanAdjustDetail(SalesPlanAdjustDetailSubTotalRequest salesPlanAdjustDetailSubTotalRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(salesPlanAdjustDetailSubTotalRequest.getPlanId());
        PageQueryPlanAdjustDetailRequest pageQueryPlanAdjustDetailRequest = new PageQueryPlanAdjustDetailRequest();
        BeanUtils.copyProperties(salesPlanAdjustDetailSubTotalRequest,pageQueryPlanAdjustDetailRequest);
        enichQueryPlanAdjustDetailRequest(pageQueryPlanAdjustDetailRequest,salesPlan);

        SalesPlanAdjustDetailSubTotalRequest subTotalAdjustRequest = new SalesPlanAdjustDetailSubTotalRequest();
        BeanUtils.copyProperties(pageQueryPlanAdjustDetailRequest,subTotalAdjustRequest);
        SalesPlanSubTotalResponse salesPlanSubTotalResponse = salesPlanAdjustDetailRepository.subTotalSalesPlanAdjustDetail(subTotalAdjustRequest);
        BigDecimal discount = (new BigDecimal(100).subtract(salesPlan.getEstimateDiscount())).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
        if(salesPlanSubTotalResponse.getBeforeAdjustMoney()!=null){
            BigDecimal adjustMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeAdjustMoney()).multiply(discount);
            salesPlanSubTotalResponse.setAdjustMoney(adjustMoney.longValue());
        }

        //合计月度计划明细, 获取计划量，任务量，初始任务量
        SubTotalSalesPlanLineRequest subTotalPlanRequest = new SubTotalSalesPlanLineRequest();
        BeanUtils.copyProperties(pageQueryPlanAdjustDetailRequest,subTotalPlanRequest);
        subTotalPlanRequest.setPlanId(Long.valueOf(pageQueryPlanAdjustDetailRequest.getPlanId()));
        subTotalPlanRequest.setStatus(null);
        subTotalPlanRequest.setManageEmployeeIdList(StringUtils.isNotBlank(pageQueryPlanAdjustDetailRequest.getManageEmployeeId())?Lists.newArrayList(pageQueryPlanAdjustDetailRequest.getManageEmployeeId()):null);
        SalesPlanSubTotalResponse salesPlanSubTotalResponse2 = salesPlanLineRepository.subTotalSalesPlanLine(subTotalPlanRequest);
        salesPlanSubTotalResponse.setMonthCount(salesPlanSubTotalResponse2.getMonthCount());
        salesPlanSubTotalResponse.setBeforeMonthMoney(salesPlanSubTotalResponse2.getBeforeMonthMoney());
        salesPlanSubTotalResponse.setMonthMoney(salesPlanSubTotalResponse2.getMonthMoney());
        salesPlanSubTotalResponse.setTaskCount(salesPlanSubTotalResponse2.getTaskCount());
        salesPlanSubTotalResponse.setBeforeTaskMoney(salesPlanSubTotalResponse2.getBeforeTaskMoney());
        salesPlanSubTotalResponse.setTaskMoney(salesPlanSubTotalResponse2.getTaskMoney());
        salesPlanSubTotalResponse.setInitTaskCount(salesPlanSubTotalResponse2.getInitTaskCount());
        salesPlanSubTotalResponse.setInitBeforeTaskMoney(salesPlanSubTotalResponse2.getInitBeforeTaskMoney());
        if(salesPlanSubTotalResponse2.getInitBeforeTaskMoney()!=null){
            BigDecimal initTaskMoney = new BigDecimal(salesPlanSubTotalResponse2.getInitBeforeTaskMoney()).multiply(discount);
            salesPlanSubTotalResponse.setInitTaskMoney(initTaskMoney.longValue());
        }

        List<String> queryScItemIdList = CollectionUtils.isNotEmpty(subTotalAdjustRequest.getScItemIdList())?subTotalAdjustRequest.getScItemIdList():null;
        List<String> queryScItemLeafCategoryId = CollectionUtils.isNotEmpty(subTotalAdjustRequest.getScItemLeafCategoryIdList())?subTotalAdjustRequest.getScItemLeafCategoryIdList():null;
        //合计crm回复量
        SubTotalCompanyReturnCountRequest subTotalReturnCountRequest = new SubTotalCompanyReturnCountRequest();
        subTotalReturnCountRequest.setPlanId(Long.valueOf(salesPlanAdjustDetailSubTotalRequest.getPlanId()));
        subTotalReturnCountRequest.setScItemIdList(queryScItemIdList);
        subTotalReturnCountRequest.setScItemLeafCategoryIdList(queryScItemLeafCategoryId);
        SubTotalCompanyReturnCountResponse subTotalCompanyReturnCountResponse = planScItemExtendService.subTotalCompanyReturnCount(subTotalReturnCountRequest);
        salesPlanSubTotalResponse.setReturnCount(getMoney(subTotalCompanyReturnCountResponse.getReturnCount()));
        salesPlanSubTotalResponse.setBeforeReturnMoney(getMoney(subTotalCompanyReturnCountResponse.getBeforeReturnMoney()));
        BigDecimal returnMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeReturnMoney()).multiply(discount);
        salesPlanSubTotalResponse.setReturnMoney(returnMoney.longValue());
        salesPlanSubTotalResponse.setReturnOutboundMoney(getMoney(subTotalCompanyReturnCountResponse.getReturnOutboundMoney()));

        //合计crm合同量
        SubTotalCompanyCrmContractCountRequest subTotalCompanyCrmContractCountRequest = new SubTotalCompanyCrmContractCountRequest();
        subTotalCompanyCrmContractCountRequest.setContractYear(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"yyyy"));
        subTotalCompanyCrmContractCountRequest.setOrgBusinessUnitCode(salesPlan.getOrgBusinessUnitCode());
        subTotalCompanyCrmContractCountRequest.setScItemIdList(queryScItemIdList);
        subTotalCompanyCrmContractCountRequest.setScItemCategoryIdList(queryScItemLeafCategoryId);
        Result<Contract> contractResult = contractService.subTotalCompanyCrmContractCount(subTotalCompanyCrmContractCountRequest);
        Contract contract = contractResult.getResult();
        setSubTotalContractCount(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"MM"),contract,salesPlanSubTotalResponse);

        return Result.success(salesPlanSubTotalResponse);
    }

    public void setSubTotalContractCount(String month, Contract contract,SalesPlanSubTotalResponse salesPlanSubTotalResponse){
        Long crmMonthContractCount = null;
        Long crmBeforeMonthContractMoney = null;
        Long crmMonthContractMoney = null;
        switch (month){
            case "01" :
                crmMonthContractCount = getCount(contract.getJanQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJanTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJanAmount());
                break;
            case "02" :
                crmMonthContractCount = getCount(contract.getFebQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getFebTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getFebAmount());
                break;
            case "03" :
                crmMonthContractCount = getCount(contract.getMarQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMarTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMarAmount());
                break;
            case "04" :
                crmMonthContractCount = getCount(contract.getAprQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAprTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAprAmount());
                break;
            case "05" :
                crmMonthContractCount = getCount(contract.getMayQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMayTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMayAmount());
                break;
            case "06" :
                crmMonthContractCount = getCount(contract.getJuneQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJuneTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJuneAmount());
                break;
            case "07" :
                crmMonthContractCount = getCount(contract.getJulyQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJulyTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJulyAmount());
                break;
            case "08" :
                crmMonthContractCount = getCount(contract.getAugQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAugTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAugAmount());
                break;
            case "09" :
                crmMonthContractCount = getCount(contract.getSeptQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getSeptTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getSeptAmount());
                break;
            case "10" :
                crmMonthContractCount = getCount(contract.getOctQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getOctTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getOctAmount());
                break;
            case "11" :
                crmMonthContractCount = getCount(contract.getNovQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getNovTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getNovAmount());
                break;
            case "12" :
                crmMonthContractCount = getCount(contract.getDecQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getDecTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getDecAmount());
                break;
            default:
                crmMonthContractCount = 0L;
                crmBeforeMonthContractMoney = 0L;
                crmMonthContractMoney = 0L;
        }

        salesPlanSubTotalResponse.setCrmMonthContractCount(crmMonthContractCount);
        salesPlanSubTotalResponse.setCrmBeforeMonthContractMoney(crmBeforeMonthContractMoney);
        salesPlanSubTotalResponse.setCrmMonthContractMoney(crmMonthContractMoney);
    }

    private Long getCount(Integer i){
        if(i == null){
            return 0L;
        }
        return i.longValue();
    }

    private Long getMoney(Long l){
        if(l == null){
            return 0L;
        }
        return l;
    }

    @Override
    @FacadeInvoker
    public Result<BigDecimal> queryCompletePercent(SalesPlanAdjustDetailSubTotalRequest salesPlanAdjustDetailSubTotalRequest) {
        if (salesPlanAdjustDetailSubTotalRequest.getBizType() == null && StringUtil.isBlank(salesPlanAdjustDetailSubTotalRequest.getBizId())) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(salesPlanAdjustDetailSubTotalRequest.getBizType());
        if (byOrganizationType == null) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        switch (byOrganizationType) {
            case SALESMAN:
                salesPlanAdjustDetailSubTotalRequest.setManageEmployeeId(salesPlanAdjustDetailSubTotalRequest.getBizId());
                break;
            case SALES_DEPARTMENT:
                salesPlanAdjustDetailSubTotalRequest.setOrgSalesDepartmentCode(salesPlanAdjustDetailSubTotalRequest.getBizId());
                break;
            case SALES_CHANNEL:
                salesPlanAdjustDetailSubTotalRequest.setOrgSalesChannelCode(salesPlanAdjustDetailSubTotalRequest.getBizId());
                break;
            case SALES_ORGANIZATION:
                salesPlanAdjustDetailSubTotalRequest.setOrgSalesOrganizationCode(salesPlanAdjustDetailSubTotalRequest.getBizId());
                break;
            case BUSINESS_UNIT:
                salesPlanAdjustDetailSubTotalRequest.setOrgBusinessUnitCode(salesPlanAdjustDetailSubTotalRequest.getBizId());
                break;
            default:
        }
        return Result.success(salesPlanAdjustDetailRepository.queryCompletePercent(salesPlanAdjustDetailSubTotalRequest));
    }

    @Override
    @FacadeInvoker
    public PageQuerySalesPlanAdjustDetailResponse getSalesPlanAdjustDetailList(PageQuerySalesPlanAdjustDetailRequest pageQuerySalesPlanAdjustDetailRequest) {
        PageQuerySalesPlanAdjustDetailResponse response = PageQuerySalesPlanAdjustDetailResponse.builder().result(Lists.newArrayList()).build();
        try {
            if (pageQuerySalesPlanAdjustDetailRequest == null) {
                return response;
            }
            response = salesPlanService.pageQuerySalesPlanAdjustDetail(pageQuerySalesPlanAdjustDetailRequest);
            log.info("getSalesPlanAdjustDetailList:" + JSONObject.toJSONString(response));
            Integer total = response.getTotal();
            List result = response.getResult();
            if (!response.getSuccess() || CollectionUtils.isEmpty(result) || total == 0) {
                return response;
            }
            result = Lists.newArrayList();
            int totalPage = total % 100 == 0 ? total / 100 : total / 100 + 1;
            for (int i = 0; i < totalPage; i++) {
                pageQuerySalesPlanAdjustDetailRequest.setStart(i * 100);
                PageQuerySalesPlanAdjustDetailResponse listResponse = salesPlanService.pageQuerySalesPlanAdjustDetail(pageQuerySalesPlanAdjustDetailRequest);
                if (listResponse.getSuccess() && CollectionUtils.isNotEmpty(listResponse.getResult()) && listResponse.getTotal() != 0) {
                    result.addAll(listResponse.getResult());
                }
            }
            response.setResult(result);
            log.info("getSalesPlanAdjustDetailList:" + response.getResult().size());
            return response;
        } catch (Exception e) {
            log.info("月度计划调整明细汇总导出异常" + JSONObject.toJSONString(e));
            return PageQuerySalesPlanAdjustDetailResponse.builder().result(Lists.newArrayList()).build();
        }
    }
}
